package com.example.musicdemo.ui.activity

import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.graphics.drawable.AnimationDrawable
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.view.View
import android.widget.AdapterView
import android.widget.PopupWindow
import android.widget.SeekBar
import com.example.musicdemo.R
import com.example.musicdemo.adapter.PopAdapter
import com.example.musicdemo.base.BaseActivity
import com.example.musicdemo.model.AudioBean
import com.example.musicdemo.service.IService
import com.example.musicdemo.service.AudioService
import com.example.musicdemo.util.StringUtil
import com.example.musicdemo.widget.PlayListPopWindow
import com.example.musicdemo.widget.PopListItemView
import kotlinx.android.synthetic.main.activity_music_player_bottom.*
import kotlinx.android.synthetic.main.activity_music_player_middle.*
import kotlinx.android.synthetic.main.activity_music_player_top.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class AudioPlayActivity : BaseActivity(), View.OnClickListener, SeekBar.OnSeekBarChangeListener,
    AdapterView.OnItemClickListener,PopAdapter.PlayListListener {
    var iService: IService? = null
    private var mDuration: Int = 0
    private var mAudioBean: AudioBean? = null
    private var mDrawable: AnimationDrawable? = null
    val MSG_PROGRESS = 0
    private val conn by lazy { AudioConnection() }
    val mPlayListener:PopAdapter.PlayListListener? = null
    private var mPopWindow:PlayListPopWindow? = null
    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg?.what) {
                MSG_PROGRESS -> startUpdateProgress()
            }
        }
    }

    override fun initListener() {
        //播放状态切换
        state.setOnClickListener(this)
        ivBack.setOnClickListener { finish() }
        //进度条变化监听
        skProgress.setOnSeekBarChangeListener(this)
        //播放模式点击事件
        mode.setOnClickListener(this)
        //上一曲和下一曲点击事件
        pre.setOnClickListener(this)
        next.setOnClickListener(this)
        //播放列表
        playlist.setOnClickListener(this)
        lyricView.setProgressListener {
            if(lyricView.getPlayFlag()) {
                iService?.seekTo(it)
                //更新进度显示
                updateProgress(it)
            }
        }
    }

    override fun initData() {
        //注册eventBus
        EventBus.getDefault().register(this)
        //通过audioService播放音乐
        val intent = intent
        intent.setClass(this,AudioService::class.java)
        //通过intent将list以及position传递过去
        bindService(intent,conn, Context.BIND_AUTO_CREATE)
        //再開啓
        startService(intent)
    }





    /**
     * 開始更新進度
     */
    private fun startUpdateProgress() {
        //獲取当前进度
        val progress: Int = iService?.getProgress() ?: 0
        //更新进度数据
        updateProgress(progress)
        //定时获取进度
        mHandler.sendEmptyMessage(MSG_PROGRESS)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_audio_player
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.state -> updatePlayState()
            R.id.mode -> updatePlayMode()
            R.id.pre -> iService?.playPre()
            R.id.next -> iService?.playNext()
            R.id.playlist -> showPlayList()
        }

    }

    /**
     * 显示播放列表
     */
    private fun showPlayList() {
        val list = iService?.getPlayList()
        list?.let {
            val adapter = PopAdapter(list,this)
            val bottomH = audio_player_bottom.height
             mPopWindow = PlayListPopWindow(this, adapter,this,window)
            mPopWindow!!.showAsDropDown(audio_player_bottom,0,-bottomH)

        }

    }

    /**
     * 更新播放模式
     */
    private fun updatePlayMode() {
        iService?.updatePlayMode()
        updatePlayModeBtn()
    }


    /**
     * 根据播放模式修改播放图标
     */
    private fun updatePlayModeBtn() {
        iService?.let {
            when(it.getPlayMode()){
                AudioService.MODE_ALL -> mode.setImageResource(R.drawable.selector_btn_playmode_order)
                AudioService.MODE_SINGLE->mode.setImageResource(R.drawable.selector_btn_playmode_single)
                AudioService.MODE_RANDOM->mode.setImageResource(R.drawable.selector_btn_playmode_random)
            }
        }
    }


    /**
     * 更新播放状态
     */
    private fun updatePlayState() {
        //更新播放状态
        iService?.updatePlayState()
        //更新播放状态的图标
        updatePlayStateBtn()
    }


    /**
     * 根据播放状态更新图标
     */
    private fun updatePlayStateBtn() {
        //获取当前播放状态
        val isPlaying = iService?.isPlaying()
        isPlaying?.let {
            if (isPlaying) {
                //播放了他
                state.setImageResource(R.drawable.selector_btn_audio_play)
                //开始博凡动画
                mDrawable?.start()
                //开始更新进度
                mHandler.sendEmptyMessage(MSG_PROGRESS)
            } else {
                //暂停
                state.setImageResource(R.drawable.selector_btn_audio_pause)
                //停止播放动画
                mDrawable?.stop()
                //停止更新进度条
                mHandler.removeMessages(MSG_PROGRESS)
            }
        }
    }


    /**
     * 进度改变的回调
     */
    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        if (!fromUser) {
            return
        }
        iService?.seekTo(progress)
        //更新界面显示
        updateProgress(progress)

    }


    /**
     * 根据当前进度数据更新界面
     */
    private fun updateProgress(progress: Int) {
        //更新进度数据
        tvProgress.text =
            StringUtil.parseDuration(progress) + "/" + StringUtil.parseDuration(mDuration)
        //更新进度数据
        skProgress.progress = progress
        //更新歌词播放进度
        lyricView.updateProgress(progress)

    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {


    }

    /**
     * 接收eventBus方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(itemBean:AudioBean){
        //歌词
        lyricView.setSongName(itemBean.display_name)
        //记录播放歌曲bean
        this.mAudioBean = itemBean
        //歌曲名字
        audio_title.text = itemBean.display_name
        //歌手名
        artist.text = itemBean.artist
        //更新播放状态按钮
        updatePlayStateBtn()
        //动画播放
        mDrawable = iv_audio_anim.drawable as AnimationDrawable
        mDrawable?.start()
        //获取总进度
        mDuration = iService?.getDuration()?:0
        //歌词
        lyricView.setSongDuration(mDuration)
        skProgress.max =mDuration
        //更新播放进度
        startUpdateProgress()
        //更新播放模式图标
        updatePlayModeBtn()
    }

    /**
     * 弹出播放列表条目的点击事件
     */
    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        //播放当前歌曲
        iService?.playPosition(position)

    }

    override fun onDestroy() {
        super.onDestroy()
            //手动解绑服务
        unbindService(conn)
        //反注册eventBus
        EventBus.getDefault().unregister(this)
        mHandler.removeCallbacksAndMessages(null)
    }

    inner class AudioConnection:ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            iService = service as IService
        }

        /**
         * 意外断开连接时候
         */
        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    override fun onPlay(position: Int) {
        iService?.playPosition(position)
        mPopWindow?.dismiss()
    }

    override fun onDelete(position: Int) {
    }

}